<template>
  <!-- 蒙层背景 -->
  <div
    class="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-10"
  >
    <!-- 弹窗主体 -->
    <div class="bg-white rounded-lg w-full max-w-sm shadow-lg p-6 relative">
      <!-- 顶部提示 -->
      <p class="text-lg font-medium text-gray-800 text-center mb-4">
        请尽快完成签到
      </p>

      <!-- 倒计时显示 -->
      <div class="text-center my-8">
        <div class="font-mono text-7xl font-bold text-gray-900 tracking-wide">
          {{ formattedTime }}
        </div>
      </div>

      <!-- 底部提示 -->
      <p class="text-center text-gray-500 text-sm mb-8">
        错过可能会导致无法领取奖励
      </p>

      <!-- 签到按钮 -->
      <van-button
        type="primary"
        block
        round
        class="!bg-blue-600 hover:!bg-blue-700 active:!bg-blue-800 transition-colors"
        :loading="loading"
        loading-text="签到中..."
        @click="handleCheckIn"
      >
        立即签到
      </van-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from "vue";
const props = defineProps({
  remainingTime: {
    type: Number,
    required: true
  },
  loading: {
    type: Boolean,
    required: true
  }
});
const remainingTime = ref(props.remainingTime);
const formattedTime = ref("");
let timer = null;
const emit = defineEmits(["timeout", "success"]);

// 暂停和恢复倒计时的函数
const pauseTimer = () => {
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
};

const resumeTimer = () => {
  if (!timer) {
    timer = setInterval(updateTimer, 1000);
  }
};

const updateTimer = () => {
  if (remainingTime.value <= 0) {
    clearInterval(timer);
    emit("timeout");
    return;
  }

  remainingTime.value--; // Move this line before formatting time

  const minutes = Math.floor(remainingTime.value / 60)
    .toString()
    .padStart(2, "0");
  const seconds = (remainingTime.value % 60).toString().padStart(2, "0");
  formattedTime.value = `${minutes}:${seconds}`;
};

// 签到处理
// const loading = ref(false);

const handleCheckIn = async () => {
  // loading.value = true;
  // pauseTimer(); // 暂停倒计时

  emit("success");

  // resumeTimer(); // 失败时恢复倒计时
};
watch(
  () => props.loading,
  newVal => {
    if (newVal) {
      pauseTimer();
    } else {
      resumeTimer();
    }
  }
);

onMounted(() => {
  updateTimer();
  timer = setInterval(updateTimer, 1000);
});

onBeforeUnmount(() => {
  if (timer) clearInterval(timer);
});
</script>

<style>
/* 微调数字间距 */
.font-mono {
  letter-spacing: -0.05em;
}

/* 覆盖Vant按钮默认样式 */
.van-button--primary {
  @apply !text-white !border-none;
}
</style>
